package tech.summerly.weather.component.fragments

import android.Manifest
import android.arch.lifecycle.ViewModelProviders
import android.content.Intent
import android.os.Bundle
import android.support.v4.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import kotlinx.android.synthetic.main.fragment_empty_city_prompt.view.*
import org.jetbrains.anko.support.v4.toast
import tech.summerly.weather.R
import tech.summerly.weather.component.activities.UserRegionManagerActivity
import tech.summerly.weather.component.viewmodel.UserRegionViewModel
import tech.summerly.weather.model.Region
import tech.summerly.weather.model.UserRegion
import tech.summerly.weather.util.getLocationWithDialog
import tech.summerly.weather.util.requestPermission
import tech.summerly.weather.util.setOnclickListenerSafely

/**
 * 当 app 启动时未检测到保存的城市信息时，就会显示当前fragment来提示用户添加城市
 */
class EmptyCityPromptFragment : Fragment() {

    companion object {

        fun newInstance(): EmptyCityPromptFragment {
            return EmptyCityPromptFragment()
        }

    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.fragment_empty_city_prompt, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) = with(view) {

        buttonAdd.setOnClickListener {
            val intent = Intent(context, UserRegionManagerActivity::class.java)
            intent.putExtra(UserRegionManagerActivity.ACTION_ADD_CITY, true)
            startActivity(intent)
        }

        buttonPositioning.setOnclickListenerSafely {
            if (activity?.requestPermission(Manifest.permission.ACCESS_FINE_LOCATION) != true) {
                toast("需要定位权限")
                return@setOnclickListenerSafely
            }
            val region = activity?.getLocationWithDialog()
            if (region == null) {
                toast("无法获取当前所处位置")
            } else {
                onNewCity(region)
            }
        }
    }

    private fun onNewCity(region: Region) {
        ViewModelProviders.of(this, UserRegionViewModel).get(UserRegionViewModel::class.java).add(UserRegion.new(region))
    }

}
